/**
 * updated 2022/03/20
 */
import axios from 'axios'

const TIMEOUT = 5000
const TIMEOUT_UPLOAD = TIMEOUT * 10
const post = function (url, params, data, headers) {
  return request('post', url, params, data, headers)
}

const get = function (url, params, data, headers) {
  return request('get', url, params, data, headers)
}

const upload = function (url, form, headers) {
  return request('post', url, undefined, form, headers, TIMEOUT_UPLOAD)
}

function request(method, url, params, data, headers, timeout = TIMEOUT) {
  const localHeaders = {}
  for (var o in headers) {
    localHeaders[o] = headers[o]
  }
  console.debug(
    new Date() +
      '--' +
      method +
      ':[url] ' +
      url +
      ' [param] ' +
      JSON.stringify(params) +
      ' [data] ' +
      JSON.stringify(data) +
      ' [header]: ' +
      JSON.stringify(localHeaders)
  )
  return new Promise((resolve, reject) => {
    axios({
      method,
      url,
      data,
      params,
      timeout,
      headers: localHeaders
    })
      .then((res) => {
        resolve(res.data)
      })
      .catch((res) => {
        const errObj = {
          msg: `网络异常（${res}），请检查设备网络！`,
          detail: res
        }
        if (res.response) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx
          errObj.msg = `服务器响应异常（${res.response.status}），请联系开发者！`
        } else if (res.request) {
          // The request was made but no response was received
          // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
          // http.ClientRequest in node.js
          errObj.msg = `网络异常(${res})，请联系开发者！`
        } else {
          // Something happened in setting up the request that triggered an Error
          console.log('Error', res.message)
        }

        reject(errObj)
      })
  })
}

//清除所有cookie函数
function clearAllCookie() {
  var date = new Date()
  date.setTime(date.getTime() - 10000)
  var keys = document.cookie.match(/[^ =;]+(?==)/g)

  if (keys) {
    for (var i = keys.length; i--; ) document.cookie = keys[i] + '=0; expire=' + date.toGMTString() + '; path=/'
  }
}

/**
 * 获取 cookie
 * @param {*} name
 */
function getCookie(name) {
  const value = `; ${document.cookie}`
  const parts = value.split(`; ${name}=`)
  if (parts.length === 2) {
    return parts.pop().split(';').shift()
  }
}

function dateFormat(date, fmt) {
  if (null == date || undefined == date) return ''
  var o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(), //日
    'h+': date.getHours(), //小时
    'm+': date.getMinutes(), //分
    's+': date.getSeconds(), //秒
    S: date.getMilliseconds() //毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
  return fmt
}

Date.prototype.toJSON = function () {
  return dateFormat(this, 'yyyy-MM-dd hh:mm:ss')
}

export default {
  request,
  get,
  post,
  upload,
  getCookie,
  clearAllCookie
}
